<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;

class File
{
    /**
     * @param string $url
     * @param string $filename
     * @return string
     */
    public static function downloadFromUrl(string $url, string $filename): string
    {
        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();

        $filep = storage_path('download');
        if (!is_dir($filep)) {
            mkdir($filep, 0755);
        }
        $newfile = $filep . '/' . $filename;
        $fp = fopen($newfile, 'a');
        fwrite($fp, $img);
        fclose($fp);
        Log::info('下载文件成功 url:' . $url);
        return $newfile;
    }

    /**
     * @param string $filename
     * @param string $ext
     * @return resource|false
     */
    public static function imagecreateByExt(string $filename, string $ext)
    {
        switch ($ext) {
            case 'jpg':
            case 'jpeg':
                return imagecreatefromjpeg($filename);
            case 'png':
                return imagecreatefrompng($filename);
            case 'gif':
                return imagecreatefromgif($filename);
            case 'bmp':
                return imagecreatefrombmp($filename);
            default:
                return false;
        }
    }
}
